package liming.ai.code.v4.core;

import liming.ai.code.v4.data.BaseConfig;
import liming.ai.code.v4.data.Context;
import liming.ai.code.v4.data.JavaCode;
import liming.ai.data.deepseek.ChatCompletionRequest;
import liming.tool.file.FileRW;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class RunnableCore {
    public static void build(List<JavaCode> javaCodeList, Context context) throws IOException, InterruptedException {
        for (JavaCode javaCode : javaCodeList) {
            if (context.isVersion(javaCode)) {
                FileRW.writeTextFile(javaCode.getJavaFile(), javaCode.getCode(), false);
                FileRW.writeTextFile(javaCode.getMdFile(), javaCode.getMd(), false);
                context.add(javaCode);
            }
        }

        String cmd = String.format("javac -encoding %s -d %s -sourcepath %s -cp %s %s",
                "utf-8",
                BaseConfig.getClassesPath(),
                BaseConfig.getJavasPath(),
                BaseConfig.getClassesPath(),
                context.getAllJavaFilePath());
        System.out.println("文件编译中 " + cmd);
        Process compileProcess = Runtime.getRuntime().exec(cmd);
        // 读取错误流的线程（提前消费避免进程阻塞）
        StringBuilder errorMessage = new StringBuilder();
        Thread errorThread = new Thread(() -> {
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(compileProcess.getErrorStream(), FileRW.FileEncoding.AUTO.getValue()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    errorMessage.append(line).append("\n");
                }
            } catch (IOException e) {
                errorMessage.append("无法读取错误流: ").append(e.getMessage());
            }
        });
        errorThread.start();
        int exitCode = compileProcess.waitFor();
        errorThread.join();  // 确保错误流读取完成
        if (exitCode != 0) {
            throw new RuntimeException("cmd: " + cmd + "\n编译错误[" + exitCode + "]:\n" + errorMessage);
        }
        System.out.println("文件编译完成 " + cmd);
    }
    public static void handleThrowable(Context context,Throwable throwable) {
        ChatCompletionRequest chatCompletionRequest = QueryCore.newCodeRequest();
        String format = String.format("%s\n" +
                "当前异常:\n%s\n",context.getAllFileInfo(),FileRW.getStackTrace(throwable));
        JSONObject response = QueryCore.valueOf(QueryCore.chat(format, chatCompletionRequest));
        while (response.has("files")){
            StringBuilder sb = new StringBuilder();
            for (Object file : response.getJSONArray("files")) {
                String readString;
                try {
                    readString = FileRW.readTextFile(new File(file.toString())).getContent();
                } catch (IOException ex) {
                    readString ="文件读取失败 "+ex;
                }
                sb.append(String.format("文件: %s\n" +
                        "内容: \n%s\n", file, readString)).append("\n");
            }
            response = QueryCore.valueOf(QueryCore.chat(sb.append("修补之前出错的位置").toString(),chatCompletionRequest));
        }
        try {
            build(JavaCode.loads(response.getJSONArray("classes")),context);
        } catch (Exception e) {
            handleThrowable(context,e);
        }
        System.out.printf("执行完毕");
    }
}
